/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: MailBox
 * Author:   zengjian
 * Date:     2018/8/31 14:09
 * Description: 信箱投递类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.yinxue.util.event;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 〈信箱投递类〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/8/31 14:09
 */
public class MailBox {

    /**
     * 信箱队列，如果需要可以创建多个
     */
    private Map<String, BlockingQueue<String>> mailBoxMap = new ConcurrentHashMap<>();
    public String defaultMailBox = "default_mailbox";
    private ArrayBlockingQueue<String> messageBox = new ArrayBlockingQueue(1000);
    private ReentrantLock lock = new ReentrantLock();

    public MailBox() {
        mailBoxMap.put(defaultMailBox, messageBox);
    }

    public boolean sendMessage(String message) {
        lock.lock();
        try {
            mailBoxMap.get(defaultMailBox).offer(message);
        } finally {
            lock.unlock();
        }
        return true;
    }

    public String acceptMessage() {
        try {
            return mailBoxMap.get(defaultMailBox).take();
        } catch (InterruptedException e) {
            Thread.interrupted();
            return "";
        }
    }

}